const net = require('net')

const server = net.createServer()
const port = 89
const host = 'localhost'

server.listen(port, host)
server.on('listening', () => {
    // console.log(`${host}:${port}`)
})

const TransformCode = require('./TransformCode')
const transformer = new TransformCode()
server.on('connection', (socket) => {
    let buffer =  null
    let len = 0
    socket.on('data', (chunk) => {
       if(buffer){
          chunk = Buffer.concat([buffer,chunk])
       }
       while(len = transformer.getLen(chunk)){
          const content = chunk.slice(0,len)
          chunk = chunk.slice(len)
          const res = transformer.decode(content)
          console.log(res)
          socket.write(transformer.encode(res.body))
       }
       buffer = chunk
    })
})

// server.on('close', () => {
//     console.log('close')
// })
// server.on('error', (err) => {
//     if(err.code === 'EADDRINUSE'){
//         console.log('端口占用')
//     }else{
//         console.log(err)
//     }
// })
